package net.yuanmomo.socket.bio;

import net.yuanmomo.socket.Constant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * Created by Hongbin.Yuan on 2016-07-03 14:26.
 */

public class TimeServeClient {
    public static void main(String[] args) {
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;

        BufferedReader userIn = null;
        try {
            socket = new Socket(Constant.HOST,Constant.PORT);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(),true);

            userIn = new BufferedReader(new InputStreamReader(System.in));

            String userInput  = null;
            userInput = userIn.readLine();
            while(userInput != null
                    && ! "".equalsIgnoreCase(userInput)){
                out.println(userInput);
                System.out.println(String.format(" send to server with [%s]  ", userInput));

                String response = in.readLine();
                if(response == null || "".equalsIgnoreCase(response)){
                    break;
                }
                System.out.println(String.format("currentTime is %s ", response));
                userInput = userIn.readLine();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(socket != null){
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (userIn != null) {
                try {
                    userIn.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                out.close();
            }
        }
    }
}
